import os
import random

from selenium.webdriver.common.by import By

from Case.python_ui.Common.basepage import Basepage
from Case.python_ui.PageLocate.admin_pu_usergroup_locator import AdminPUUserGroupLocator
from selenium.common.exceptions import StaleElementReferenceException
from Case.python_ui.Common.commontool import CommonTool
from Case.python_ui.Test_data.menu_name_data import MenuName
from Case.python_ui.Test_data.usergroup_data import UserGroup
import time
import datetime
from datetime import timedelta
from datetime import datetime as dt


class AdminPUUserGroupPages(Basepage):

    # 进入usergroup页面
    def enter_the_usergroup_page(self):
        doc = '进入admin端的首页'
        for i in range(3):
            try:
                self.wait_elevisble(AdminPUUserGroupLocator.paltform_user_tab, doc)
                self.click_element(AdminPUUserGroupLocator.paltform_user_tab, doc)
                self.wait_elevisble(AdminPUUserGroupLocator.user_group_tab, doc)
                self.click_element(AdminPUUserGroupLocator.user_group_tab, doc)
                break
            except:
                self.refresh_page()
                time.sleep(5)
                continue
        self.wait_elevisble(AdminPUUserGroupLocator.user_group_title, doc)

    # 查询usergroup
    def query_user_group(self, usergroup):
        doc = '查询用户组'
        self.wait_elevisble(AdminPUUserGroupLocator.user_group_search_input, doc)
        self.keyboard_event(AdminPUUserGroupLocator.user_group_search_input, doc)
        self.send_keys(AdminPUUserGroupLocator.user_group_search_input, usergroup, doc)
        time.sleep(5)
        self.click_query_button()

        # 点击查询按钮

    def click_query_button(self):
        doc = '点击查询按钮'
        self.wait_elevisble(AdminPUUserGroupLocator.user_group_search_button, doc)
        self.click_element(AdminPUUserGroupLocator.user_group_search_button, doc)
        time.sleep(3)

        # 创建user group

    def create_user_group(self):
        doc = '创建用户组'
        time.sleep(5)
        self.refresh_page()
        self.enter_the_usergroup_page()
        time.sleep(2)
        self.click_element(AdminPUUserGroupLocator.add_user_group, doc)
        create_user_groupname = CommonTool.generate_string()
        print(create_user_groupname)
        self.wait_elevisble(AdminPUUserGroupLocator.user_group_name, doc)
        self.send_keys(AdminPUUserGroupLocator.user_group_name, create_user_groupname, doc)
        self.wait_elevisble(AdminPUUserGroupLocator.user_select, doc)
        self.click_element(AdminPUUserGroupLocator.user_select, doc)
        time.sleep(5)
        self.wait_elevisble(AdminPUUserGroupLocator.chooice_user, doc)
        self.click_element(AdminPUUserGroupLocator.chooice_user, doc)
        time.sleep(2)
        self.click_element(AdminPUUserGroupLocator.add_user_group_ok, doc)
        self.wait_elevisble(AdminPUUserGroupLocator.add_success_prompt, doc)
        self.query_user_group(create_user_groupname)
        self.click_query_button()
        return create_user_groupname

    # 删除创建的usergroup
    def delete_user_group(self, usergroup):
        doc = '删除创建的用户组'
        time.sleep(5)
        self.refresh_page()
        self.enter_the_usergroup_page()
        self.query_user_group(usergroup)
        self.get_action_list(usergroup)
        self.move_mouse_to_click_element(AdminPUUserGroupLocator.action_list, doc)
        self.wait_elevisble(AdminPUUserGroupLocator.action_delete, doc)
        self.click_element(AdminPUUserGroupLocator.action_delete, doc)
        time.sleep(5)
        self.click_element(AdminPUUserGroupLocator.delete_acknowledge, doc)
        time.sleep(2)
        self.click_element(AdminPUUserGroupLocator.delete_confirm, doc)
        self.wait_elevisble(AdminPUUserGroupLocator.add_success_prompt, doc)

    def get_action_list(self, usergroup):
        doc = '获取操作列表'
        for i in range(3):
            try:
                self.wait_elevisble(AdminPUUserGroupLocator.action_list, doc)
                break
            except:
                self.driver.refresh()
                self.query_user_group(usergroup)

    # 获取查询出来的usergroup的值
    def get_user_group_text(self):
        doc = '获取用户组名称'
        self.wait_elevisble(AdminPUUserGroupLocator.user_group_text, doc)
        search_result = self.get_element(AdminPUUserGroupLocator.user_group_text, doc).text
        return search_result

    # 获取查询出来的删除usergroup的值
    def get_delet_user_group_text(self):
        doc = '获取查询出来的删除usergroup的值'
        search_result = self.get_elements(AdminPUUserGroupLocator.user_group_text, doc)
        return search_result

    def add_user_to_group(self, org_name):
        doc = '将用户加入用户组'
        time.sleep(5)
        self.refresh_page()
        self.enter_the_usergroup_page()
        self.wait_elevisble(AdminPUUserGroupLocator.add_user_group, doc)
        self.click_element(AdminPUUserGroupLocator.add_user_group, doc)
        create_user_groupname = CommonTool.generate_string()
        print(create_user_groupname)
        self.wait_elevisble(AdminPUUserGroupLocator.user_group_name, doc)
        self.send_keys(AdminPUUserGroupLocator.user_group_name, create_user_groupname, doc)
        self.wait_elevisble(AdminPUUserGroupLocator.user_select, doc)
        self.click_element(AdminPUUserGroupLocator.user_select, doc)
        time.sleep(3)
        self.send_keys(AdminPUUserGroupLocator.user_select_input, org_name, doc)
        time.sleep(2)
        self.click_create_user()
        time.sleep(2)
        self.click_element(AdminPUUserGroupLocator.user_group_name, doc)
        time.sleep(4)
        self.click_element(AdminPUUserGroupLocator.delete_confirm, doc)
        self.wait_elevisble(AdminPUUserGroupLocator.add_success_prompt, doc)
        return create_user_groupname

    def click_create_user(self):
        doc = '点击创建的user'
        eles = self.get_elements(AdminPUUserGroupLocator.user_click, doc)
        eles[-1].click()
        time.sleep(3)

    # 编辑用户组
    def edit_user_group(self, cmdopt):
        doc = '编辑用户组'
        time.sleep(5)
        self.refresh_page()
        time.sleep(3)
        self.wait_elevisble(AdminPUUserGroupLocator.action_list, doc)
        self.click_element(AdminPUUserGroupLocator.action_list, doc)
        self.wait_elevisble(AdminPUUserGroupLocator.action_edit, doc)
        self.click_element(AdminPUUserGroupLocator.action_edit, doc)
        self.wait_elevisble(AdminPUUserGroupLocator.user_group_edit_name, doc)
        self.keyboard_event(AdminPUUserGroupLocator.user_group_edit_name, doc)
        time.sleep(5)
        self.send_keys(AdminPUUserGroupLocator.user_group_name_edit, UserGroup.deit_user_group_name, doc)
        time.sleep(2)
        self.click_element(AdminPUUserGroupLocator.delete_confirm, doc)
        time.sleep(3)
        self.wait_elevisble(AdminPUUserGroupLocator.add_success_prompt, doc)
        self.query_user_group(UserGroup.deit_user_group_name)
        self.click_query_button()
        edit_group_name = self.get_user_group_text()
        return edit_group_name

    def remove_user(self, usergroup, cmdopt):
        doc = '删除用户组下面的用户'
        max_attempts = 3
        attempts = 0
        delete_num = 0
        while attempts < max_attempts:
            try:
                self.refresh_page()
                self.enter_the_usergroup_page()
                self.query_user_group(usergroup)
                eles = self.get_elements(AdminPUUserGroupLocator.remove_user, doc)
                if len(eles) == 0 or delete_num >= 5:
                    break
                else:
                    for ele in eles:
                        if ele.text == 'Remove User':
                            self.driver.execute_script("arguments[0].scrollIntoView({ block: 'center', inline: 'end' });", ele)
                            ele.click()
                            self.wait_elevisble(AdminPUUserGroupLocator.delete_acknowledge, doc)
                            self.click_element(AdminPUUserGroupLocator.delete_acknowledge, doc)
                            time.sleep(2)
                            self.click_element(AdminPUUserGroupLocator.delete_confirm, doc)
                            self.wait_elevisble(AdminPUUserGroupLocator.add_success_prompt, doc)
                            delete_num = delete_num + 1
            except  StaleElementReferenceException:
                attempts += 1

    # 验证列表字段 和 status列的值
    def list_columns(self):
        doc = "验证admin端user group列表字段"

        self.enter_the_usergroup_page()
        self.wait_elevisble(AdminPUUserGroupLocator.list_columns, doc)
        list_columns = self.get_elements(AdminPUUserGroupLocator.list_columns, doc)
        assert list_columns[0].text == "Account Email"
        assert self.get_element(AdminPUUserGroupLocator.list_column_status, doc).text == "Status"
        assert list_columns[2].text == "User Name"
        assert list_columns[3].text == "Phone Number"
        assert list_columns[4].text.startswith("Creation Time")
        assert list_columns[5].text == "Actions"

        self.wait_elevisble(AdminPUUserGroupLocator.status_checkbox, doc)
        self.click_by_js(AdminPUUserGroupLocator.status_checkbox, doc)
        self.wait_elevisble(AdminPUUserGroupLocator.status_checkbox_options, doc)
        status_options = self.get_elements(AdminPUUserGroupLocator.status_checkbox_options, doc)
        assert status_options[0].text == "Normal"
        assert status_options[1].text == "Locked"
        assert status_options[2].text == "Inactive"

        assert self.get_element(AdminPUUserGroupLocator.remove_user_button, doc).text == "Remove User"

    # 点击email跳转至用户具体信息界面
    def click_email(self):
        time.sleep(3)
        self.refresh_page()
        time.sleep(5)
        doc = "点击email进入用户具体信息界面"
        email_text = self.get_element(AdminPUUserGroupLocator.email_button, doc).text
        self.click_by_js(AdminPUUserGroupLocator.email_button, doc)

        time.sleep(3)
        self.wait_elevisble(AdminPUUserGroupLocator.user_info_page_title, doc)
        print(email_text)
        print(self.get_element(AdminPUUserGroupLocator.user_info_page_title, doc).text)
        assert self.get_element(AdminPUUserGroupLocator.user_info_page_title, doc).text == email_text

    def enter_enterprise_user_group(self):
        doc = "进入Enterprise User Group页面"
        for i in range(3):
            try:
                self.wait_elevisble(AdminPUUserGroupLocator.enterprise_user_tab, doc)
                self.click_element(AdminPUUserGroupLocator.enterprise_user_tab, doc)
                self.wait_elevisble(AdminPUUserGroupLocator.enterprise_user_group_tab, doc)
                self.click_element(AdminPUUserGroupLocator.enterprise_user_group_tab, doc)
                break
            except:
                self.refresh_page()
                time.sleep(5)
                continue
        self.wait_elevisble(AdminPUUserGroupLocator.user_group_title, doc)
        time.sleep(3)

    def enter_enterprise_user_user(self):
        doc = "进入Enterprise User User页面"
        for i in range(3):
            try:
                self.wait_elevisble(AdminPUUserGroupLocator.enterprise_user_tab, doc)
                self.click_element(AdminPUUserGroupLocator.enterprise_user_tab, doc)
                self.wait_elevisble(AdminPUUserGroupLocator.enterprise_user_user_tab, doc)
                self.click_element(AdminPUUserGroupLocator.enterprise_user_user_tab, doc)
                break
            except:
                self.refresh_page()
                time.sleep(5)
                continue
        self.wait_eleinvisble(AdminPUUserGroupLocator.loading_wait, doc)
        time.sleep(3)

    def query_user_account(self, email_str):
        doc = "搜索Account列表"
        self.send_keys(AdminPUUserGroupLocator.enterprise_user_group_query_input, email_str, doc)
        time.sleep(1)
        self.click_element(AdminPUUserGroupLocator.enterprise_user_group_query_button, doc)
        time.sleep(1)

    def date_reverse(self, date_str: str):
        """ 倒置时间字符串 """
        data_str_list = date_str.split('-')
        data_str_list.reverse()
        return '-'.join(data_str_list)

    def filter_eu_group_user_audit(self, filter_index, if_refresh=False):
        doc = "筛选audit列表"
        if filter_index == 2:
            js = "document.getElementsByClassName('antd4-table-content')[0].scrollLeft=1000"
            self.excute_js(js)

        self.get_elements(AdminPUUserGroupLocator.EU_group_audit_filter, doc)[filter_index].click()
        time.sleep(1)
        filter_options = self.get_elements(AdminPUUserGroupLocator.EU_group_audit_filter_option, doc)
        chosen_option = random.sample(filter_options, 1)
        chosen_text = chosen_option[0].text
        chosen_option[0].click()
        time.sleep(1)
        self.click_element(AdminPUUserGroupLocator.EU_group_audit_filter_confirm, doc)
        time.sleep(1)
        rows = self.get_elements(AdminPUUserGroupLocator.EU_group_audit_rows, doc)

        for row in rows:
            if filter_index == 0:
                assert row.find_element(By.XPATH, "./td[2]").text == chosen_text
            elif filter_index == 1:
                assert row.find_element(By.XPATH, "./td[4]").text == chosen_text
            elif filter_index == 2:
                assert row.find_element(By.XPATH, "./td[7]").text == chosen_text
        if if_refresh:
            self.refresh_page()
            time.sleep(5)
            self.click_element(AdminPUUserGroupLocator.enterprise_user_group_audit_tab, doc)
            self.wait_eleinvisble(AdminPUUserGroupLocator.loading_wait, doc)

    def enterprise_user_group_filter_user_behavior(self):
        doc = "Enterprise User Group筛选用户行为"
        self.enter_enterprise_user_group()
        email_str = "Etest1@sigma.com"
        self.query_user_account(email_str)
        email_xpath = f"//span[text()='{email_str}']/.."
        self.click_element((By.XPATH, email_xpath), doc)
        time.sleep(5)
        self.click_element(AdminPUUserGroupLocator.enterprise_user_group_audit_tab, doc)
        self.wait_eleinvisble(AdminPUUserGroupLocator.loading_wait, doc)

        start_date = dt.strptime(self.date_reverse(self.get_element(AdminPUUserGroupLocator.enterprise_user_group_start_time_input, doc).get_attribute("value")), "%Y-%m-%d")
        end_date = dt.strptime(self.date_reverse(self.get_element(AdminPUUserGroupLocator.enterprise_user_group_end_time_input, doc).get_attribute("value")), "%Y-%m-%d")

        rows = self.get_elements(AdminPUUserGroupLocator.EU_group_audit_rows, doc)
        for row in rows:
            assert dt.strptime(self.date_reverse(row.find_element(By.XPATH, "./td[8]").text[0:10]), "%Y-%m-%d") >= start_date
            assert dt.strptime(self.date_reverse(row.find_element(By.XPATH, "./td[9]").text[0:10]), "%Y-%m-%d") <= end_date

        self.filter_eu_group_user_audit(0, True)
        self.filter_eu_group_user_audit(1, True)
        self.filter_eu_group_user_audit(2)

    def eu_user_download_user(self, cmdopt):
        doc = "下载Enterprise User User用户数据"
        self.enter_enterprise_user_user()
        self.click_element(AdminPUUserGroupLocator.EU_user_download, doc)

        time.sleep(8)
        file_name = "User"
        list_of_files = os.listdir(MenuName.download_path[cmdopt])
        latest_file = list_of_files[-1]
        assert latest_file.startswith(file_name) and latest_file.endswith(".xls")